package com.hm.cms.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.stereotype.Service;

import com.hm.cms.mongo.domain.CmsBaseInfo;
import com.hm.cms.mongo.domain.QCmsBaseInfo;
import com.hm.cms.mongo.vo.CmsBaseInfoVo;
import com.hm.cms.share.repository.mongo.CmsBaseInfoRepository;
import com.hm.cms.share.service.CmsBaseInfoService;
import com.hm.common.common.BeanUtil;
import com.hm.common.exception.ErrorCode;
import com.hm.common.exception.ServiceException;
import com.hm.common.model.PageInfo;

/**
 * @author shishun.wang
 * @date 上午10:43:25 2016年8月6日
 * @version 1.0
 * @describe
 */
@Service
public class CmsBaseInfoServiceImpl implements CmsBaseInfoService {

	@Autowired
	private CmsBaseInfoRepository cmsBaseInfoRepository;

	@Override
	public CmsBaseInfoVo getCmsBaseInfo(String id) {
		CmsBaseInfo cmsBaseInfo = cmsBaseInfoRepository.findOne(id);
		if (null == cmsBaseInfo) {
			throw ServiceException.warning(ErrorCode.DATA_NOT_FOUND);
		}

		return (CmsBaseInfoVo) BeanUtil.copyProperties(new CmsBaseInfoVo(), cmsBaseInfo);
	}

	@Override
	public String addCmsBaseInfo(CmsBaseInfoVo baseInfoVo, String operationUser) {
		CmsBaseInfo cmsBaseInfo = new CmsBaseInfo();
		{
			cmsBaseInfo = (CmsBaseInfo) BeanUtil.copyProperties(new CmsBaseInfo(), baseInfoVo);
			cmsBaseInfo.setCreateUser(operationUser);
		}

		return cmsBaseInfoRepository.save(cmsBaseInfo).getId();
	}

	@Override
	public String updateCmsBaseInfo(CmsBaseInfoVo baseInfoVo, String operationUser) {
		CmsBaseInfo cmsBaseInfo = cmsBaseInfoRepository.findOne(baseInfoVo.getId());
		if (null == cmsBaseInfo) {
			throw ServiceException.warning(ErrorCode.DATA_NOT_FOUND);
		}
		cmsBaseInfo = (CmsBaseInfo) BeanUtil.copyProperties(cmsBaseInfo, baseInfoVo);

		return cmsBaseInfoRepository.save(cmsBaseInfo).getId();
	}

	@Override
	public String deleteCmsBaseInfo(CmsBaseInfoVo baseInfoVo, String operationUser) {
		cmsBaseInfoRepository.delete(baseInfoVo.getId());
		return baseInfoVo.getId();
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public PageInfo<CmsBaseInfoVo> queryCmsBaseInfo(Integer pageNumber, Integer pageSize) {

		PageInfo<CmsBaseInfoVo> pageInfo = new PageInfo<CmsBaseInfoVo>(pageNumber, pageSize);

		Pageable pageable = new QPageRequest(pageInfo.getPageNumber(), pageInfo.getPageSize(),
				QCmsBaseInfo.cmsBaseInfo.createTime.desc());
		Page page = cmsBaseInfoRepository.findAll(pageable);

		List<CmsBaseInfoVo> vos = new ArrayList<CmsBaseInfoVo>();
		page.getContent().forEach(baseInfo -> {
			vos.add((CmsBaseInfoVo) BeanUtil.copyProperties(new CmsBaseInfoVo(), baseInfo));
		});

		return pageInfo.execute(page, vos);
	}
}
